package com.example.todolist.controller;

import cn.hutool.core.util.StrUtil;
import com.example.todolist.base.R;
import com.example.todolist.dto.*;
import com.example.todolist.entity.TodoItemModel;
import com.example.todolist.service.TodoItemService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/todo-items")
public class TodoItemController {

    @Resource
    private TodoItemService service;


    @PostMapping("/addTodoItem")
    public R addTodoItem(@RequestBody final AddTodoItemRequest request) {
        if (StrUtil.isEmpty(request.getContent())) {
            return R.failed("参数为空");
        }

        final TodoParameter parameter = TodoParameter.of(request.getContent());
        final TodoItemModel todoItem = this.service.addTodoItem(parameter);

        return R.success();
    }

    @PutMapping("/{id}")
    public R markAsDone(@PathVariable("id") final int id, @RequestBody final MarkAsDoneRequest request) {
        if (id <= 0) {
            return R.failed("索引小于等于0");
        }

        if (!request.isDone()) {
            return R.failed("已经完成");
        }

        final Optional<TodoItemModel> todoItem = this.service.markTodoItemDone(TodoIndexParameter.of(id));

        if (todoItem.isPresent()) {
            return R.success();
        }

        return R.failed();
    }

    @GetMapping("/list")
    public List<TodoItemResponse> list(@RequestParam(value = "all", defaultValue = "false") final boolean all) {
        final List<TodoItemModel> items = this.service.showList(all);
        return items.stream().map(TodoItemResponse::new).collect(Collectors.toList());
    }
}
